import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import api from "@/api"
import Cookies from 'js-cookie'
import store from '@/store'
// import menuList from "@/config/menuConfig";
// import { menuItem } from "@/config/menuConfig";
const routes: Array<RouteRecordRaw> = [
  {
    path: '/:pathMatch(.*)',
    name: "Login",
    component: () => import(/* webpackChunkName: "login" */ "../views/login/login.vue"),
  },
  {
    path: '/index',
    name: "index",
    component: () => import(/* webpackChunkName: "index" */ "../views/index.vue"),
    children: [
      {
        path: '/home',
        name: "home",
        component: () => import(/* webpackChunkName: "home" */ "../views/Home/home.vue"),
      },
      {
        path: '/user',
        name: "user",
        component: () => import(/* webpackChunkName: "user" */ "../views/User/user.vue"),
      },
      {
        path: '/role',
        name: "role",
        component: () => import(/* webpackChunkName: "role" */ "../views/Role/role.vue"),
      },
    ]
  },

];

// 将menu配置 放置到meta中
/* const merge = (menu: menuItem[], route: RouteRecordRaw[] = []) => {
  for (let j of menu) {
    for (let i of route) {
      if (i.path == j.key) {
        console.log(i, j);

        i.meta = { name: j.name, icon: j.icon, index: i.path }
        if (j.children && i.children) {
          if (Array.isArray(j.children)) {
            merge(j.children, i.children)
          } else {
            merge(Object.values(j.children).flat(), i.children)
          }
        }
      }
    }
  }
} */
// merge(menuList, routes[1].children)

// 创建路由
const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  if (!from.name && to.name != 'Login') {//刷新或重新打开就进行登陆验证
    if (Cookies.get("storage") == "true") {
      await api.login({
        account: Cookies.get("account"),
        parssWord: Cookies.get("password")
      }).then((res: any) => {
        if (res.code == 200) {
          return next()
        } else {
          return next({ name: "Login" })
        }
      })
    } else {
      next({ name: "Login" })
    }
  } else {
    next()
  }
})


router.beforeResolve(async to => {
  store.commit('setRouterPath', to.path)
  store.commit('setTabIndex', to.path)
})

export default router;
